<template>
  <el-dialog
    :before-close="close"
    :width="dialogWidth"
    :title="title"
    :visible.sync="editDialog"
    v-if="editDialog"
    center
    v-dialogDrag
  >
    <el-form :model="form" ref="form" :rules="rules" class="mt20">
      <el-col :span="8" class="mb10">
        <el-form-item label="编号：" prop="number" :label-width="formLabelWidth">
          <el-input v-model="form.number" autocomplete="off" placeholder="请输入编号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="客户电话：" prop="phone" label-width="95px">
          <el-input v-model="form.phone" autocomplete="off" placeholder="请输入客户电话"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="客户电话1：" prop="phone1" label-width="100px">
          <el-input v-model="form.phone1" autocomplete="off" placeholder="请输入客户电话1"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="客户电话2：" prop="phone2" label-width="100px">
          <el-input v-model="form.phone2" autocomplete="off" placeholder="请输入客户电话2"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="客户姓名：" prop="name" label-width="95px">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="身份证号：" prop="idCard" label-width="95px">
          <el-input v-model="form.idCard" autocomplete="off" placeholder="请输入客户身份证号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="渠道来源：" prop="promotionName" label-width="95px">
          <el-select placeholder="请选择渠道来源" v-model="form.promotionName">
            <el-option v-for="item in promotionList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="区域：" prop="distributionName" label-width="95px">
          <el-select placeholder="请选择区域" v-model="form.distributionName">
            <el-option v-for="item in distributionList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="现居地：" prop="homeAddress" label-width="95px">
          <el-input v-model="form.homeAddress" autocomplete="off" placeholder="请输入现居地"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="上户地址：" prop="registerAddress" label-width="95px">
          <el-input v-model="form.registerAddress" autocomplete="off" placeholder="请输入上户地址"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="用车区域：" prop="useArea" label-width="95px">
          <el-input v-model="form.useArea" autocomplete="off" placeholder="请输入用车区域"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="车牌号：" prop="licensePlateNumber" label-width="95px">
          <el-input v-model="form.licensePlateNumber" autocomplete="off" placeholder="请输入车牌号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="车架号：" prop="frameNumber" label-width="95px">
          <el-input v-model="form.frameNumber" autocomplete="off" placeholder="请输入车架号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="购买车型：" prop="cartype" label-width="95px">
          <el-input v-model="form.cartype" autocomplete="off" placeholder="请输入购买车型"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="权证专员：" prop="warrantMan" label-width="95px">
          <el-select placeholder="请选择权证专员姓名" v-model="form.warrantMan">
            <el-option v-for="item in warrantManList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="指导价：" prop="guidancePrice" label-width="95px">
          <el-input v-model="form.guidancePrice" autocomplete="off" placeholder="请输入指导价"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="保险公司：" prop="insuranceCompany" label-width="95px">
          <el-input v-model="form.insuranceCompany" autocomplete="off" placeholder="请输入保险公司名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="贷款机构：" prop="loanCompany" label-width="95px">
          <el-select placeholder="请选择贷款机构名称" v-model="form.loanCompany">
            <el-option key="无" label="无" value="无"></el-option>
            <el-option v-for="item in trialList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="还款金额：" prop="installment" label-width="95px">
          <el-input v-model="form.installment" autocomplete="off" placeholder="请输入还款金额"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="贷款金额：" prop="loanAmount" label-width="95px">
          <el-input v-model="form.loanAmount" autocomplete="off" placeholder="请输入贷款金额"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="贷款期数：" prop="loanPeriod" label-width="95px">
          <el-input v-model="form.loanPeriod" autocomplete="off" placeholder="请输入贷款期数"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="中心：" prop="center" :label-width="formLabelWidth">
          <el-select placeholder="请选择中心名" v-model="form.center" @change="getDeptList">
            <el-option v-for="item in centerList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="部门：" prop="dept" :label-width="formLabelWidth">
          <el-select placeholder="请选择部门名" v-model="form.dept" @change="getSalesmanList">
            <el-option v-for="item in deptList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="业务员：" prop="salesman" label-width="90px">
          <el-select placeholder="请选择业务员名" v-model="form.salesman">
            <el-option v-for="item in salesmanList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="完件日期：" prop="complateTime" label-width="90px">
          <div class="block">
            <el-date-picker
              v-model="form.complateTime"
              align="right"
              type="date"
              placeholder="请选择完件日期"
              :picker-options="pickerOptions1"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="签单日期：" prop="signTime" label-width="90px">
          <div class="block">
            <el-date-picker
              v-model="form.signTime"
              align="right"
              type="date"
              placeholder="请选择签单日期"
              :picker-options="pickerOptions1"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="投保日期：" prop="insuranceTime" label-width="90px">
          <div class="block">
            <el-date-picker
              v-model="form.insuranceTime"
              align="right"
              type="date"
              placeholder="请选择投保日期"
              :picker-options="pickerOptions1"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="还款日期：" prop="installmentTime" label-width="90px">
          <div class="block">
            <el-date-picker
              v-model="form.installmentTime"
              align="right"
              type="date"
              placeholder="请选择还款日期"
              :picker-options="pickerOptions1"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="交车凭证：" prop="deliveryVoucher" label-width="95px">
          <el-upload
            ref="upload1"
            class="upload-demo"
            action
            :auto-upload="false"
            :file-list="fileList"
            :limit="1"
            :on-success="uploadSuccess"
            :on-error="uploadErr"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过200kb</div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="交车照片：" prop="deliveryPhoto" label-width="95px">
          <el-upload
            ref="upload2"
            class="upload-demo"
            action
            :auto-upload="false"
            :file-list="fileList1"
            :limit="1"
            :on-success="uploadSuccess"
            :on-error="uploadErr"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过200kb</div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb10">
        <el-form-item label="备注：" prop="remarks" label-width="95px">
          <el-input type="textarea" v-model="form.remarks" autocomplete="off" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-col>
    </el-form>
    <span slot="footer" class="dialog-footer align-center tiling inline-block mt10 mb10">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handleConfirm('form')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import "../utils/drag.js";
import { pickerOptions1 } from "@/../config/Stats_options";

export default {
  name: "warrant_dialog",
  data() {
    var vIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入客户身份证号！"));
      } else if (
        value.search(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/) === -1
      ) {
        return callback(new Error("身份证号填写有误！"));
      } else {
        return callback();
      }
    };
    var vCartype = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入购买车型！"));
      } else if (value.length < 2) {
        return callback(new Error("长度在 2-30 个字符"));
      } else if (value.length > 30) {
        return callback(new Error("长度在 2-30 个字符"));
      } else {
        return callback();
      }
    };
    var vName = (min, max) => {
      return (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入客户姓名！"));
        } else if (value.search(/^[\u0391-\uFFE5]+$/) === -1) {
          return callback(new Error("请输入中文！"));
        } else if (value.length < min) {
          return callback(new Error(`长度在 ${min}-${max}个汉字`));
        } else if (value.length > max) {
          return callback(new Error(`长度在 ${min}-${max}个汉字`));
        } else {
          return callback();
        }
      };
    };
    var vNumber = (min, max) => {
      return (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入编号！"));
        } else if (value.toString().search(/^[0-9]*$/) === -1) {
          return callback(new Error("请输入数字！"));
        } else if (value.length < min) {
          return callback(new Error(`长度在 ${min}-${max}个数字`));
        } else if (value.length > max) {
          return callback(new Error(`长度在 ${min}-${max}个数字`));
        } else {
          return callback();
        }
      };
    };
    var vPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入客户电话！"));
      } else if (value.toString().search(/^(13|14|15|17|18|19)\d{9}$/) === -1) {
        return callback(new Error("请输入11位电话号码！"));
      } else {
        return callback();
      }
    };
    var vLength = (min, max) => {
      return (rule, value, callback) => {
        if (value.length < min) {
          return callback(new Error(`长度在 ${min}-${max}个字符`));
        } else if (value.length > max) {
          return callback(new Error(`长度在 ${min}-${max}个字符`));
        } else {
          return callback();
        }
      };
    };

    return {
      form: {
        number: "",
        complateTime: "",
        signTime: "",
        name: "",
        idCard: "",
        phone: "",
        phone1: "",
        phone2: "",
        promotionName: "",
        distributionName: "",
        homeAddress: "",
        registerAddress: "",
        useArea: "",
        licensePlateNumber: "",
        center: "",
        dept: "",
        salesman: "",
        cartype: "",
        warrantMan: "",
        frameNumber: "",
        guidancePrice: "",
        insuranceTime: "",
        insuranceCompany: "",
        loanCompany: "",
        installment: "",
        installmentTime: "",
        loanAmount: "",
        loanPeriod: "",
        deliveryVoucher: "",
        deliveryPhoto: "",
        remarks: ""
      },
      fileList: [],
      fileList1: [],
      rules: {
        name: { validator: vName(2, 8), trigger: "blur" },
        number: { validator: vNumber(1, 8), trigger: "blur" },
        promotionName: {
          required: true,
          message: "请输入渠道来源！",
          trigger: "blur"
        },
        phone: { validator: vPhone, trigger: "blur" },
        phone1: { validator: vLength(0, 11), trigger: "blur" },
        phone2: { validator: vLength(0, 11), trigger: "blur" },
        idCard: { validator: vIdCard, trigger: "blur" },
        frameNumber: { validator: vLength(0, 20), trigger: "blur" },
        licensePlateNumber: { validator: vLength(1, 8), trigger: "blur" },
        homeAddress: { validator: vLength(0, 20), trigger: "blur" },
        registerAddress: { validator: vLength(0, 20), trigger: "blur" },
        useArea: { validator: vLength(0, 20), trigger: "blur" },
        loanAmount: { validator: vLength(0, 8), trigger: "blur" },
        insuranceCompany: { validator: vLength(0, 10), trigger: "blur" },
        installment: { validator: vLength(0, 8), trigger: "blur" },
        guidancePrice: { validator: vLength(0, 8), trigger: "blur" },
        loanPeriod: { validator: vLength(0, 5), trigger: "blur" },
        remarks: { validator: vLength(0, 20), trigger: "blur" },
        cartype: { validator: vCartype, trigger: "blur" },
        center: {
          required: true,
          message: "请选择中心！",
          trigger: "blur"
        },
        dept: {
          required: true,
          message: "请选择部门！",
          trigger: "blur"
        },
        salesman: {
          required: true,
          message: "请选择业务员！",
          trigger: "blur"
        }
      },
      pickerOptions1,
      warrantManList: [],
      trialList: [],
      centerList: [],
      deptList: [],
      distributionList: [],
      salesmanList: [],
      promotionList: [],
      isCancell: false,
      formLabelWidth: "70px",
      dialogWidth: "1000px",
      flag: false
    };
  },
  created() {
    this.getCenterList();
    this.getPromotionList();
    this.getWarrantManList();
    this.getTrialList();
    this.getDistributionList();
  },
  computed: {
    imgName1() {
      return `${this.form.phone}.jpg`;
    }
  },
  watch: {
    editDialog() {
      this.form = {
        id: this.archivesForm.id,
        number: this.archivesForm.number,
        complateTime: this.archivesForm.complateTime,
        signTime: this.archivesForm.signTime,
        name: this.archivesForm.name,
        idCard: this.archivesForm.idCard,
        phone: this.archivesForm.phone,
        phone1: this.archivesForm.phone1,
        phone2: this.archivesForm.phone2,
        promotionName: this.archivesForm.promotionName,
        distributionName: this.archivesForm.distributionName,
        homeAddress: this.archivesForm.homeAddress,
        registerAddress: this.archivesForm.registerAddress,
        useArea: this.archivesForm.useArea,
        licensePlateNumber: this.archivesForm.licensePlateNumber,
        center: this.archivesForm.centerName,
        dept: this.archivesForm.deptName,
        salesman: this.archivesForm.salesmanName,
        cartype: this.archivesForm.cartype,
        warrantMan: this.archivesForm.warrantMan,
        frameNumber: this.archivesForm.frameNumber,
        guidancePrice: this.archivesForm.guidancePrice,
        insuranceTime: this.archivesForm.insuranceTime,
        insuranceCompany: this.archivesForm.insuranceCompany,
        loanCompany: this.archivesForm.loanCompany,
        installment: this.archivesForm.installment,
        installmentTime: this.archivesForm.installmentTime,
        loanAmount: this.archivesForm.loanAmount,
        loanPeriod: this.archivesForm.loanPeriod,
        deliveryVoucher: this.archivesForm.deliveryVoucher,
        deliveryPhoto: this.archivesForm.deliveryPhoto,
        remarks: this.archivesForm.remarks
      };
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 205 / 205 < 1;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 200kb!");
      }
      return isJPG && isLt2M;
    },
    uploadErr(err) {
      if (err) {
        this.$message.error("上传失败!");
      }
    },
    uploadSuccess(response, file) {
      if (response.id === 101) {
        this.$notify({
          title: "成功",
          message: "上传成功！",
          type: "success",
          duration: "600"
        });
      }
    },
    getDistributionList() {
      this.$axios.get("/api/system/distributions").then(data => {
        this.distributionList = data.map(item => {
          return item.name;
        });
      });
    },
    getDeptList() {
      this.form.dept = "";
      this.form.salesman = "";
      this.$axios.post("/api/system/departmentList", this.form).then(data => {
        this.deptList = data.map(item => {
          return item.name;
        });
      });
    },
    getSalesmanList() {
      this.form.salesman = "";
      this.$axios.post("/api/system/salesmanList", this.form).then(data => {
        this.salesmanList = data.map(item => {
          return item.name;
        });
      });
    },
    getPromotionList() {
      this.$axios.get("/api/system/promotions").then(data => {
        this.promotionList = data.map(item => {
          return item.name;
        });
      });
    },
    getCenterList() {
      this.$axios.get("/api/system/centers").then(data => {
        this.centerList = data.map(item => {
          return item.name;
        });
      });
    },
    getWarrantManList() {
      this.$axios.get("/api/system/warrantMans").then(data => {
        this.warrantManList = data.map(item => {
          return item.name;
        });
      });
    },
    getTrialList() {
      this.$axios.get("/api/system/trials").then(data => {
        this.trialList = data.map(item => {
          return item.name;
        });
      });
    },
    handleConfirm(formName) {
      // 先进行表单验证
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.editArchives();
        }
      });
    },
    editArchives() {
      const file1 = this.$refs.upload1.uploadFiles[0];
      const file2 = this.$refs.upload2.uploadFiles[0];
      const formData = new FormData();

      if (file1) {
        formData.append("file", file1.raw);
      }

      if (file2) {
        formData.append("file", file2.raw);
      }

      formData.append("form", JSON.stringify(this.form));
      this.$axios.post("/api/archives/editArchive/", formData).then(data => {
        if (data.status) {
          this.$notify({
            title: "成功",
            message: "上传成功！",
            type: "success",
            duration: "600"
          });
          this.$emit("update");
          this.close();
        } else {
          this.$message({
            type: "error",
            message: data.msg
          });
          this.close();
        }
      });
    },
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        number: "",
        complateTime: "",
        signTime: "",
        name: "",
        idCard: "",
        phone: "",
        phone1: "",
        phone2: "",
        promotionName: "",
        distributionName: "",
        homeAddress: "",
        registerAddress: "",
        useArea: "",
        licensePlateNumber: "",
        center: "",
        dept: "",
        salesman: "",
        cartype: "",
        warrantMan: "",
        frameNumber: "",
        guidancePrice: "",
        insuranceTime: "",
        insuranceCompany: "",
        loanCompany: "",
        installment: "",
        installmentTime: "",
        loanAmount: "",
        loanPeriod: "",
        deliveryVoucher: "",
        deliveryPhoto: "",
        remarks: ""
      };
    }
  },
  props: ["editDialog", "title", "archivesForm"]
};
</script>
<style scoped>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
